package com.ruoyi.inspection.controller;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.YnStatusEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.inspection.config.GovernTaskConfig;
import com.ruoyi.inspection.config.JobStatusEnum;
import com.ruoyi.inspection.domain.receiveVo.ReceiveJobAttachment;
import com.ruoyi.inspection.domain.receiveVo.ReceiveJobPlan;
import com.ruoyi.inspection.domain.receiveVo.ReceiveJobTicket;
import com.ruoyi.inspection.domain.receiveVo.ReceiveJobTicketVideo;
import com.ruoyi.system.domain.AppCreateJobBill;
import com.ruoyi.system.domain.JobPlanBillDeclare;
import com.ruoyi.system.domain.TemporaryStaffAccount;
import com.ruoyi.system.entity.AppJobExplanPdfPath;
import com.ruoyi.system.mapper.AppCreateJobBillMapper;
import com.ruoyi.system.mapper.JobPlanBillDeclareMapper;
import com.ruoyi.system.mapper.PushInfoMapper;
import com.ruoyi.system.mapper.TemporaryStaffAccountMapper;
import com.ruoyi.system.service.AppCreateJobBillService;
import com.ruoyi.system.service.AppJobExplanPdfPathService;
import com.ruoyi.system.service.JobPlanBillDeclareService;
import com.ruoyi.system.service.PDFService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 作业票上报市局
 */
@Slf4j
@RestController
@RequestMapping("/govern/job/")
public class GovernJobPlanBillPush {
    @Autowired
    private PDFService pdfService;
    @Autowired
    private PushInfoMapper pushInfoMapper;
    @Autowired
    private AppCreateJobBillMapper appCreateJobBillMapper;
    @Autowired
    private JobPlanBillDeclareMapper jobPlanBillDeclareMapper;
    @Autowired
    private TemporaryStaffAccountMapper temporaryStaffAccountMapper;
    @Autowired
    private AppJobExplanPdfPathService appJobExplanPdfPathService;

    // 定义默认手机号常量
    private static final String DEFAULT_MOBILE = "13718992906";

    /*******************作业计划 * 每天推送一次 *作业计划 ****************/
    @Scheduled(cron = "0 0 21 * * ?")
    public void JobPlanBillScheduleTask() {
        pushJobPlanBill();
    }

    /*******************作业票证 * 每天推送一次 *作业票证 ****************/
    @Scheduled(cron = "0 15 21 * * ?")
    public void JobBillScheduleTask() {
        pushJobBillTicket();
    }

    /*******************作业视频 * 每天推送一次 *作业视频 ****************/
    @Scheduled(cron = "0 35 21 * * ?")
    public void JobBillVideoScheduleTask() {
        pushJobTicketVideo();
    }

    /*******************作业附件 * 每天推送一次 *作业附件 ****************/
    @Scheduled(cron = "0 55 21 * * ?")
    public void JobBillAttachmentScheduleTask() {
        pushJobTicketAttachment();
    }

//    // 作业附件上报
//    @ApiOperation("作业附件上报")
//    @GetMapping("/attach")
//    public AjaxResult pushJobAttachment() throws Exception {
//        pushJobTicketAttachment();
//        return AjaxResult.success();
//    }

    /**
     * 推送作业计划 到市局
     */
    public void pushJobPlanBill() {
        // 查询待推送的作业票数据
        JobPlanBillDeclare searchVo = new JobPlanBillDeclare();
        searchVo.setYn(YnStatusEnum.Y.getCode());
        searchVo.setIsUpload(0);
        List<JobPlanBillDeclare> jobPlanList = jobPlanBillDeclareMapper.queryAll(searchVo);
        if (StringUtils.isEmpty(jobPlanList)) {
            log.info("推送市局端 : 没有作业计划数据要推送！！！");
            return;
        }

        List<ReceiveJobPlan> resultList = new ArrayList<>();
        for (JobPlanBillDeclare jobPlan : jobPlanList) {
            ReceiveJobPlan planVO = ReceiveJobPlan.jobPlanBillToReceiveJobPlan(jobPlan);
            if (planVO==null) { continue; }
            planVO.setPersonId(handleWorkerPersonIds(planVO.getWorkerName()));
            resultList.add(planVO);
        }

        // 市局推送作业票数据
        String url = GovernTaskConfig.receiveJobPlanUrl;
        String s = GovernTaskConfig.pushData(JSONUtil.toJsonPrettyStr(resultList), url);
        pushInfoMapper.insert(s);
        // 更新上报状态
        jobPlanList.forEach(plan -> {
            JobPlanBillDeclare updateEntity = new JobPlanBillDeclare();
            updateEntity.setGovernId(plan.getGovernId());
            updateEntity.setId(plan.getId());
            updateEntity.setIsUpload(1);
            jobPlanBillDeclareMapper.update(updateEntity);
        });
    }

    /**
     * 推送作业票证 到市局
     */
    public void pushJobBillTicket() {
        // 查询待推送的作业票数据
        AppCreateJobBill appCreateJobBill = new AppCreateJobBill();
        appCreateJobBill.setIsUpload(0);
        List<AppCreateJobBill> jobBillList = appCreateJobBillMapper.queryAll(appCreateJobBill);
        if (StringUtils.isEmpty(jobBillList)) {
            log.info("推送市局端 : 没有作业票数据要推送！！！");
            return;
        }

        List<ReceiveJobTicket> resultList = new ArrayList<>();
        for (AppCreateJobBill jobTicket : jobBillList) {
            String specialNum = jobTicket.getSpecialNumber();
            JobPlanBillDeclare jobPlan = selectJobPlanBillDeclare(specialNum);
            if (jobPlan == null) {
                continue;
            }
            ReceiveJobTicket ticketVo = ReceiveJobTicket.convertToReceiveJobTicket(jobTicket, jobPlan);
            if (ticketVo == null) {
                continue;
            }
            ticketVo.setPersonId(handleWorkerPersonIds(ticketVo.getWorkerName()));
            handleResponsiblePersonMobile(ticketVo, jobPlan.getPhone());
            resultList.add(ticketVo);
        }

        // 市局推送作业票数据
        String url = GovernTaskConfig.receiveJobTicketUrl;
        String s = GovernTaskConfig.pushData(JSONUtil.toJsonPrettyStr(resultList), url);
        pushInfoMapper.insert(s);
        // 更新上报状态
        jobBillList.forEach(jobBill -> {
            AppCreateJobBill updateEntity = new AppCreateJobBill();
            updateEntity.setGovernId(jobBill.getGovernId());
            updateEntity.setId(jobBill.getId());
            String ticketStatus = jobBill.getTicketStatus();
            updateEntity.setIsUpload(0);
            if (JobStatusEnum.YYS.getCode().equals(ticketStatus)
                    || JobStatusEnum.ZF.getCode().equals(ticketStatus)) {
                updateEntity.setIsUpload(1);
            }
            appCreateJobBillMapper.update(updateEntity);
        });
    }

    /**
     * 推送作业视频 到市局
     */
    public void pushJobTicketVideo() {
        AppCreateJobBill appCreateJobBill = new AppCreateJobBill();
        appCreateJobBill.setIsUploadVideo(0);
        appCreateJobBill.setIsUpload(1);
        List<AppCreateJobBill> jobBillList = appCreateJobBillMapper.queryAll(appCreateJobBill);

        pushJobTicketVideo(jobBillList);
    }

    /**
     * 作业视频业务（推送作业视频 到市局）
     *
     * @param jobBillList
     */
    public void pushJobTicketVideo(List<AppCreateJobBill> jobBillList) {
        if (StringUtils.isEmpty(jobBillList)) {
            log.info("推送市局端 : 没有作业票视频数据要推送！！！");
            return;
        }

        List<ReceiveJobTicketVideo> resultList = new ArrayList<>();
        for (AppCreateJobBill jobTicket : jobBillList) {
            ReceiveJobTicketVideo videoVo = ReceiveJobTicketVideo.convertAppCreateJobBill(jobTicket);
            if (videoVo == null) {
                continue;
            }
            resultList.add(videoVo);
        }

        // 市局推送作业票数据
        String url = GovernTaskConfig.receiveJobVideoUrl;
        String s = GovernTaskConfig.pushData(JSONUtil.toJsonPrettyStr(resultList), url);
        pushInfoMapper.insert(s);
        // 更新上报状态
        jobBillList.forEach(jobBill -> {
            AppCreateJobBill updateEntity = new AppCreateJobBill();
            updateEntity.setGovernVideoId(jobBill.getGovernVideoId());
            updateEntity.setId(jobBill.getId());
            updateEntity.setIsUploadVideo(1);
            appCreateJobBillMapper.update(updateEntity);
        });
    }

    /**
     * 推送作业附件 到市局
     */
    public void pushJobTicketAttachment() {
        AppCreateJobBill appCreateJobBill = new AppCreateJobBill();
        appCreateJobBill.setIsUploadAttach(0);
        appCreateJobBill.setIsUpload(1);
        List<AppCreateJobBill> jobBillList = appCreateJobBillMapper.queryAll(appCreateJobBill);

        if (StringUtils.isEmpty(jobBillList)) {
            log.info("推送市局端 : 没有作业票附件数据要推送!");
            return;
        }

        List<ReceiveJobAttachment> resultList = new ArrayList<>();
        for (AppCreateJobBill jobTicket : jobBillList) {
            if (null == jobTicket.getJobType()) {
                continue;
            }

            // 根据作业票类型查询pdf路径
            int jobType = Integer.valueOf(jobTicket.getJobType());
            AppJobExplanPdfPath jobPdf = appJobExplanPdfPathService.queryById(jobType);
            String base64 = pdfService.readJobPdfToBase64(jobTicket, jobPdf);

            ReceiveJobAttachment attachmentVo = ReceiveJobAttachment.convertReceiveJobAttachment(jobTicket);
            if (attachmentVo == null) {
                continue;
            }

            attachmentVo.setFileName(jobPdf.getFileName());
            attachmentVo.setFileType("application/pdf");
            attachmentVo.setAttachment(base64);
            resultList.add(attachmentVo);
        }

        // 市局推送作业票数据
        String url = GovernTaskConfig.receiveJobAttachmentUrl;
        String s = GovernTaskConfig.pushData(JSONUtil.toJsonPrettyStr(resultList), url);
        pushInfoMapper.insert(s);

        // 更新上报状态
        jobBillList.forEach(jobBill -> {
            AppCreateJobBill updateEntity = new AppCreateJobBill();
            updateEntity.setGovernAttachId(jobBill.getGovernAttachId());
            updateEntity.setId(jobBill.getId());
            updateEntity.setIsUploadAttach(1);
            appCreateJobBillMapper.update(updateEntity);
        });

    }

    /**
     * 处理负责人手机号信息
     */
    /**
     * 处理作业人员ID集合
     */
    private String handleWorkerPersonIds(String workerName) {
        if (StringUtils.isEmpty(workerName)) {
            return null;
        }

        return Arrays.stream(workerName.split(","))
                .filter(StringUtils::isNotEmpty) // 过滤空字符串
                .map(name -> {
                    TemporaryStaffAccount account = temporaryStaffAccountMapper.queryByName(name);
                    if (account == null) {
                        log.warn("未查询到员工[{}]对应的临时账户信息", name);
                        return null;
                    }
                    return account.getGovernId();
                })
                .filter(StringUtils::isNotEmpty) // 过滤无效ID
                .collect(Collectors.joining(","));
    }

    /**
     * 处理负责人手机号信息
     */
    private void handleResponsiblePersonMobile(ReceiveJobTicket ticketVo, String mobile) {
        // 如果手机号无效，则从临时员工账户查询
        if (StringUtils.isEmpty(mobile) || mobile.length() < 11) {
            TemporaryStaffAccount account = temporaryStaffAccountMapper.queryByName(ticketVo.getTicketResponsName());
            if (account != null) {
                mobile = account.getPhone();
            }
            // 确保手机号有效
            mobile = StringUtils.isNotEmpty(mobile) && mobile.length() == 11 ? mobile : DEFAULT_MOBILE;
        }

        ticketVo.setMajorPersonMobile(mobile);
    }


    /**
     * 查询作业计划
     *
     * @param billNumber
     * @return
     */
    public JobPlanBillDeclare selectJobPlanBillDeclare(String billNumber) {
        JobPlanBillDeclare jobPlanBillDeclare = new JobPlanBillDeclare();
        jobPlanBillDeclare.setYn(YnStatusEnum.Y.getCode());
        jobPlanBillDeclare.setBillNumber(billNumber);

        List<JobPlanBillDeclare> jobPlanBillDeclares
                = jobPlanBillDeclareMapper.queryAll(jobPlanBillDeclare);
        if (StringUtils.isEmpty(jobPlanBillDeclares)) {
            log.info("推送市局端 : 没有找到作业票: {} 对应的作业计划！！！", billNumber);
            return null;
        }

        return jobPlanBillDeclares.get(0);
    }


}
